package com.laggou.redisclusterdemo.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Configuration
@ConditionalOnClass({JedisCluster.class})
@ConfigurationProperties(prefix = "spring.redis.cluster")
public class JedisClusterConfig {

    List<String> nodes;

    int timeout;

    public List<String> getNodes() {
        return nodes;
    }

    public void setNodes(List<String> nodes) {
        this.nodes = nodes;
    }

    public int getTimeout() {
        return timeout;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    @Bean
    public JedisCluster getJedisCluster(){
        Set<HostAndPort> hostAndPorts = new HashSet<>();

        nodes.forEach(node -> {
            String[] split = node.split(":");
            hostAndPorts.add(new HostAndPort(split[0].trim(), Integer.valueOf(split[1].trim())));
        });

        return new JedisCluster(hostAndPorts, timeout);
    }



}
